#!/usr/bin/env node

const fs = require('fs')
const path = require('path')

// 分析构建结果
function analyzeBundle() {
    const distPath = path.join(__dirname, '../dist')

    if (!fs.existsSync(distPath)) {
        console.log('❌ dist目录不存在，请先运行 npm run build')
        return
    }

    console.log('📊 构建分析报告')
    console.log('================')

    // 分析文件大小
    const files = getAllFiles(distPath)
    const totalSize = files.reduce((sum, file) => sum + file.size, 0)

    console.log(`📁 总文件数: ${files.length}`)
    console.log(`📦 总大小: ${formatBytes(totalSize)}`)
    console.log('')

    // 按类型分组
    const jsFiles = files.filter(f => f.name.endsWith('.js'))
    const cssFiles = files.filter(f => f.name.endsWith('.css'))
    const imageFiles = files.filter(f => /\.(png|jpg|jpeg|gif|svg|webp)$/i.test(f.name))
    const otherFiles = files.filter(f => !jsFiles.includes(f) && !cssFiles.includes(f) && !imageFiles.includes(f))

    console.log('📊 文件类型分析:')
    console.log(`  JS文件: ${jsFiles.length} 个, ${formatBytes(jsFiles.reduce((s, f) => s + f.size, 0))}`)
    console.log(`  CSS文件: ${cssFiles.length} 个, ${formatBytes(cssFiles.reduce((s, f) => s + f.size, 0))}`)
    console.log(`  图片文件: ${imageFiles.length} 个, ${formatBytes(imageFiles.reduce((s, f) => s + f.size, 0))}`)
    console.log(`  其他文件: ${otherFiles.length} 个, ${formatBytes(otherFiles.reduce((s, f) => s + f.size, 0))}`)
    console.log('')

    // 最大的文件
    const largestFiles = files
        .sort((a, b) => b.size - a.size)
        .slice(0, 10)

    console.log('🔍 最大的10个文件:')
    largestFiles.forEach((file, index) => {
        console.log(`  ${index + 1}. ${file.name} - ${formatBytes(file.size)}`)
    })
    console.log('')

    // 优化建议
    console.log('💡 优化建议:')

    const jsSize = jsFiles.reduce((s, f) => s + f.size, 0)
    const cssSize = cssFiles.reduce((s, f) => s + f.size, 0)
    const imageSize = imageFiles.reduce((s, f) => s + f.size, 0)

    if (jsSize > 1024 * 1024) { // 1MB
        console.log('  ⚠️  JS文件过大，建议进行代码分割')
    }

    if (cssSize > 200 * 1024) { // 200KB
        console.log('  ⚠️  CSS文件过大，建议提取关键CSS')
    }

    if (imageSize > 2 * 1024 * 1024) { // 2MB
        console.log('  ⚠️  图片文件过大，建议压缩图片')
    }

    const largestFile = largestFiles[0]
    if (largestFile && largestFile.size > 500 * 1024) { // 500KB
        console.log(`  ⚠️  最大文件 ${largestFile.name} 过大，建议拆分`)
    }

    console.log('  ✅ 建议启用gzip压缩')
    console.log('  ✅ 建议使用CDN加速')
    console.log('  ✅ 建议启用浏览器缓存')
}

function getAllFiles(dir, files = []) {
    const items = fs.readdirSync(dir)

    for (const item of items) {
        const fullPath = path.join(dir, item)
        const stat = fs.statSync(fullPath)

        if (stat.isDirectory()) {
            getAllFiles(fullPath, files)
        } else {
            files.push({
                name: path.relative(dir, fullPath),
                size: stat.size,
                path: fullPath
            })
        }
    }

    return files
}

function formatBytes(bytes) {
    if (bytes === 0) return '0 Bytes'

    const k = 1024
    const sizes = ['Bytes', 'KB', 'MB', 'GB']
    const i = Math.floor(Math.log(bytes) / Math.log(k))

    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

analyzeBundle()
